/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sistema.util;

import br.com.sistema.infraestrutura.CFG;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Lauro
 */
public class MultipartFormHandler {

    private ServletFileUpload handler;
    private List items;
    
    public MultipartFormHandler() throws FileUploadException {
        this.handler = getHandler();
    }
    
    private ServletFileUpload getHandler() throws FileUploadException {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         *Set the size threshold, above which content will be stored on disk.
         */
        fileItemFactory.setSizeThreshold(CFG.MAX_MEMORY_SIZE);
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(CFG.TMP_DIRECTORY);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        uploadHandler.setHeaderEncoding(CFG.ENCODING);
        uploadHandler.setSizeMax(CFG.MAX_UPLOAD_SIZE);

        return uploadHandler;
    }
    
    public boolean isMultipart(HttpServletRequest request) throws FileUploadException{
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(isMultipart){
            loadItems(request);
        }
        return isMultipart;
    }
    
    public void loadItems(HttpServletRequest request) throws FileUploadException {
        if(handler == null){
            handler = getHandler();
        }
        items = handler.parseRequest(request);
    }

    public String getParameter(String fieldName) throws UnsupportedEncodingException {
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase(fieldName)) {
                    return new String(item.getString().trim().getBytes("iso-8859-1"), "UTF-8");
                }
            }
        }
        return null;
    }

    public FileItem getFile(String fieldName) {
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase(fieldName)) {
                    return item;
                }
            }
        }
        return null;
    }
}
